import os
from typing import List

from aop.aop_timeit import timeit
from models.models_prod import OpOrderedBiddingPrice as ProdOpOrderedBiddingPriceModel
from services.dev.dev_order_bid_price_service import DevOrderBidPriceService
from services.prod.erp_mapping_services import ErpMappingService
from services.prod.prod_service import ProdService
from sync import delete_tag, sync_tag
from sync.base_sync import BaseSync
from utils.date_tuils import get_yesterday_time_range
from utils.log_utils import get_logger
from utils.sku_map_utils import order_goods_sku_map

# 获取一个命名的日志记录器
logger = get_logger(__name__, os.path.splitext(os.path.basename(__file__))[0])


class SyncOrderedBiddingPrice(BaseSync):
    def __init__(self,
                 prod_service: ProdService,
                 dev_service: DevOrderBidPriceService,
                 time_field='create_time',
                 erp_mapping_service: ErpMappingService = None
                 ):
        super().__init__(prod_service=prod_service, dev_service=dev_service)
        self.time_field = time_field
        self.erp_mapping_service = erp_mapping_service
        self.dev_service = dev_service

    def insert_dev_data(self, items: List[ProdOpOrderedBiddingPriceModel], session=None):
        sku_maps = order_goods_sku_map([order.outer_id for order in items], self.erp_mapping_service)
        self.dev_service.add(items, session=session, sku_maps=sku_maps)
        logger.info(f" 表名：{self.prod_service.get_table_name()} ,查询字段 {self.prod_service.time_field},同步完成")


@timeit(name="SyncOrderedBiddingPrice")
def main(s=None, e=None):
    """

    :param s: 开始时间
    :param e: 结束时间
    """
    try:
        if s and e:
            start, end = s, e
        else:
            start, end = get_yesterday_time_range()
        erp_mapping_service = ErpMappingService()
        prod_service = ProdService(model_class=ProdOpOrderedBiddingPriceModel, time_field='create_time')
        dev_service = DevOrderBidPriceService()
        with SyncOrderedBiddingPrice(
                prod_service,
                dev_service,
                time_field='create_time',
                erp_mapping_service=erp_mapping_service
        ) as syncer:
            syncer.show_total_count(start, end)
            if delete_tag():
                logger.info("删除指定区间的数据")
                syncer.delete_dev_data(start, end)

            if sync_tag():
                logger.info("同步指定区间数据")
                syncer.sync_page(start, end,page_size=5000)
                ## 此处使用多进程处理百万数据
                # ids = syncer.get_total_ids(start, end)
                # print('总数', len(syncer.get_total_ids(start, end)))
                # create_multiprocess_data_list(10, ids, get_datas_by_ids)

    except Exception as e:
        logger.error("主程序异常退出: %s", e, exc_info=True)


def get_datas_by_ids(ids):
    prod = ProdService(ProdOpOrderedBiddingPriceModel, 'create_time')
    total_count = len(ids)
    logger.info("开始处理数据, 共有 %s 条数据", total_count)
    # 分批处理
    step = 10000
    dev_service = DevOrderBidPriceService()
    for i in range(0, total_count, step):
        logger.info("正在处理第 %s 条到第 %s 条数据,总共 %s", i, i + step, total_count)

        result = [item[0] for item in ids[i:i + step]]
        print('result', len(result))
        # 获取指定id的数据
        data = prod.get_data_by_ids(result, prod.get_session())
        dev_service.add(data)


if __name__ == '__main__':
    main()
